<template>
    <div class="user-list-container">
        <el-card class="table-card">
            <div class="header-container">
                <el-page-header content="员工列表" icon="" title="员工管理" />
                <div class="search-container">
                    <el-input
                        v-model="searchKeyword"
                        placeholder="请输入用户名关键词"
                        clearable
                        @input="handleSearch"
                    >
                        <template #suffix>
                            <el-icon><Search /></el-icon>
                        </template>
                    </el-input>
                </div>
            </div>

            <el-table :data="paginatedData" style="width: 100%" border>
                <el-table-column prop="username" label="用户名" min-width="100" />
                <el-table-column label="头像" width="100" align="center">
                    <template #default="scope">
                        <div v-if="scope.row.avatar">
                            <el-avatar :size="50" :src="'http://localhost:3000' + scope.row.avatar"></el-avatar>
                        </div>
                        <div v-else>
                            <el-avatar :size="50"
                                src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="角色" width="100" align="center">
                    <template #default="scope">
                        <el-tag v-if="scope.row.role === 1" class="ml-2" type="danger">管理员</el-tag>
                        <el-tag v-else-if="scope.row.role === 2" class="ml-2" type="success">编辑</el-tag>
                        <el-tag v-else class="ml-2" type="info">普通员工</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="phone" label="联系电话" min-width="120" />
                <el-table-column prop="email" label="邮箱" min-width="180" />
                <el-table-column prop="location" label="现居住地" min-width="120" />
                <el-table-column prop="introduction" label="个人简介" min-width="200" show-overflow-tooltip />

                <el-table-column label="操作" fixed="right" width="150" align="center">
                    <template #default="scope">
                        <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-popconfirm title="你确定要删除吗？" confirm-button-text="确定" cancel-button-text="取消"
                            @confirm="handleDelete(scope.row)">
                            <template #reference>
                                <el-button size="small" type="danger">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="currentPage"
                    :page-size="pageSize"
                    :total="filteredData.length"
                    layout="total, prev, pager, next, jumper"
                    @current-change="handleCurrentChange"
                    background
                    small
                />
            </div>
        </el-card>

        <!-- 编辑信息弹出框 -->
        <el-dialog v-model="dialogVisible" title="编辑成员" width="50%">
            <!-- 弹出表单 -->
            <el-form ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="80px" class="demo-ruleForm"
                status-icon>
                <!-- 用户名 -->
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" />
                </el-form-item>
                <!-- 密码 -->
                <el-form-item label="密码" prop="password">
                    <el-input v-model="userForm.password" type="password" />
                </el-form-item>
                <!-- 角色 -->
                <el-form-item label="角色" prop="role">
                    <el-select v-model="userForm.role" class="m-2" placeholder="Select" style="width:100%;">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <!-- 联系电话 -->
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="userForm.phone" />
                </el-form-item>
                <!-- 邮箱 -->
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email" />
                </el-form-item>
                <!-- 现居住地 -->
                <el-form-item label="现居住地" prop="location">
                    <el-input v-model="userForm.location" />
                </el-form-item>
                <!-- 个人简介 -->
                <el-form-item label="个人简介" prop="introduction">
                    <el-input v-model="userForm.introduction" type="textarea" />
                </el-form-item>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleEditConfirm()">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import axios from 'axios';
import { Search } from '@element-plus/icons-vue';
// import { get } from 'lodash';

// 编辑弹出表单部分
const dialogVisible = ref(false);
const userFormRef = ref();
let userForm = reactive({
    username: "",
    password: "",
    role: 2,  //1 管理员 ，2 编辑
    introduction: "",
    phone: "",    // 联系电话
    email: "",    // 邮箱
    location: ""  // 现居住地
});

// 规则
const userFormRules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    role: [
        { required: true, message: '请选择角色', trigger: 'blur' },
    ],
    phone: [
        { required: false, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    email: [
        { required: false, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    location: [
        { required: false, message: '请输入现居住地', trigger: 'blur' },
    ],
    introduction: [
        { required: true, message: '请输入个人简介', trigger: 'blur' },
    ]
});

const options = [{
    label: "管理员",
    value: 1
},
{
    label: "编辑",
    value: 2
},
{
    label: "普通员工",
    value: 3
}];

// 表格数据和分页相关
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = 6; // 每页显示6条
const searchKeyword = ref('');

// 搜索功能 - 过滤数据
const filteredData = computed(() => {
    if (!searchKeyword.value) {
        return tableData.value;
    }
    return tableData.value.filter(item => 
        item.username.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
});

// 当前页的数据
const paginatedData = computed(() => {
    const startIndex = (currentPage.value - 1) * pageSize;
    return filteredData.value.slice(startIndex, startIndex + pageSize);
});

// 搜索处理函数
const handleSearch = () => {
    // 搜索时重置到第一页
    currentPage.value = 1;
};

// 分页变化处理函数
const handleCurrentChange = (val) => {
    currentPage.value = val;
};

onMounted(() => {
    getTableData();
});

const getTableData = async () => {
    const res = await axios.get("/adminapi/user/list");
    // console.log(res.data)
    tableData.value = res.data.data;
};

// 编辑回调
const handleEdit = async data => {
    // console.log(data)
    // userForm
    const res = await axios.get(`/adminapi/user/list/${data._id}`);
    console.log(res.data.data);
    // userForm = res.data.data[0]
    Object.assign(userForm, res.data.data[0]);
    dialogVisible.value = true;
};

// 编辑确认回调
const handleEditConfirm = () => {
    userFormRef.value.validate(async (valid) => {
        if (valid) {
            // console.log(userForm)
            // 1 - 更新后端
            await axios.put(`/adminapi/user/list/${userForm._id}`, userForm);
            // 2 - 弹出框隐藏
            dialogVisible.value = false;
            // 3 - 获取table数据
            getTableData();
        }
    });
};

const handleDelete = async (data) => {
    // console.log(data);
    await axios.delete(`/adminapi/user/list/${data._id}`);
    getTableData();
};
</script>

<style lang="scss" scoped>
.user-list-container {
    padding: 0;
    height: 100%;
    position: relative;
}

.table-card {
    height: 100%;
    margin: 0;
    padding: 0;
    
    :deep(.el-card__body) {
        height: 100%;
        padding: 15px;
        display: flex;
        flex-direction: column;
    }
}

.header-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.search-container {
    width: 300px;
}

.el-table {
    margin-top: 20px;
    width: 100%;
    flex: 1;
    margin-bottom: 70px; /* 为分页器预留空间 */
}

.el-page-header {
    margin-bottom: 10px;
}

.pagination-container {
    position: absolute;
    bottom: 20px;
    right: 20px;
    z-index: 10;
    background-color: white;
    padding: 5px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
}

:deep(.el-table .cell) {
    word-break: break-all;
}
</style>